package com.runjian.demo.handler;

import com.runjian.demo.base.BusinessException;
import com.runjian.demo.base.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.UUID;

/**
 * 异常处理器
 *
 * @author Admin
 */
@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {

    /**
     * BusinessException业务异常 通用处理
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String message = e.getMessage();
        log.error("请求地址: {}, 业务异常", requestURI, e);
        return Result.fail(e.getCode(), StringUtils.defaultIfBlank(message, "业务异常!"));
    }

    /**
     * 系统异常 通用处理
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String message = e.getMessage();
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        log.error("请求地址: {}, 系统异常, 错误ID: {}", requestURI, id, e);
        return Result.error("系统异常!错误ID: " + id);
    }

}
